import {makeAutoObservable} from 'mobx'
import axios from 'axios'

class ListStore {
    mainData = [] //基础数据
    menuIndex = 0 //菜单索引号
    carList = [] //购物车列表
    total = 0//购物车数量
    price = 0 //总价

    constructor() {
        // 将参数对象中的属性设置为 可观察的
        makeAutoObservable(this, {}, {autoBind: true}); //this指向实例对象.第三个参数是让this始终指向实例对象（store解构之后也不丢失）
        //获取到创建实例时传来的参数
    }


    //获取数据源
    getList() {
        axios.get('http://localhost:3004/takeaway').then(res => {
            //严格模式下，不可在请求异步数据的函数中直接修改状态
            // this.mainData = res.data
            this.setMainData(res.data)

        })
    }

    //商品加入购物车
    addShoppingCar(id) {
        this.total++
        this.mainData.some((type) => {
            type.foods.some((food => {
                if (food.id == id) {
                    this.price = this.price + food.price

                    food.orderNum ? food.orderNum++ : food.orderNum = 1
                    let flag = this.carList.some((v, i) => {
                        if (v.id == food.id) {
                            v.orderNum = food.orderNum
                            return true
                        }
                    })
                    if (!flag) {
                        this.carList.push(food)
                    }
                    return true
                }
            }))

        })
    }

    //购物车删除物品
    delShoppingCar(id) {
        //删除某个
        if (id) {
            this.total--
            this.mainData.some((type) => {
                let flag = type.foods.some(((food, i) => {
                    if (food.id == id) {
                        this.price = this.price - food.price
                        food.orderNum--
                        this.carList.some((v, i) => {
                            if (v.id == food.id) {
                                food.orderNum == 0 ? this.carList.splice(i, 1) : this.carList[i] = v
                                return true
                            }
                        })
                        return true
                    }
                }))
                return flag
            })
        } else {
            //清空购物车
            this.price = 0
            this.carList = []
            this.total = 0
            this.mainData.forEach(type => {
                type.foods.forEach(food => {
                    food.orderNum = 0
                })
            })
        }
    }

    setMainData(list) {
        this.mainData = list
    }

    //当前菜单索引号
    setMenuIndex(v) {
        this.menuIndex = v
    }
}

export default ListStore